package org.yelongframework.servlet.http;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.yelongframework.commons.io.IOUtil;

/**
 * 默认实现
 * 
 * @since 1.0.0
 */
public class DefaultHttpServletResponseSupport implements HttpServletResponseSupport {

	public static final String ATTACHMENT_FILENAME_KEY = "fileName";

	// ==================================================响应内容==================================================

	@Override
	public void responseText(HttpServletResponse response, String text, String contentType) throws IOException {
		response.setContentType(contentType);
		response.getWriter().write(text);
	}

	@Override
	public void responseByteArray(HttpServletResponse response, byte[] content) throws IOException {
		response.getOutputStream().write(content);
	}

	// ==================================================响应文件==================================================

	@Override
	public void responseFile(HttpServletResponse response, File file) throws IOException {
		responseFile(response, file, file.getName());
	}

	@Override
	public void responseFile(HttpServletResponse response, File file, String fileName) throws IOException {
		responseFile(response, new FileInputStream(file), fileName);
	}

	@Override
	public void responseFile(HttpServletResponse response, byte[] data, String fileName) throws IOException {
		responseFile(response, new ByteArrayInputStream(data), fileName);
	}

	@Override
	public void responseFile(HttpServletResponse response, InputStream inputStream, String fileName)
			throws IOException {
		responseFile(response, inputStream, IOUtil.DEFAULT_BUFFER_SIZE, fileName);
	}

	@Override
	public void responseFile(HttpServletResponse response, InputStream inputStream, int bufferSize, String fileName)
			throws IOException {
		if (bufferSize < 0) {
			throw new IllegalArgumentException("缓冲区大小不能小于0");
		}
		response.setCharacterEncoding("UTF-8");
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.setHeader("Content-Disposition", "attachment;" + ATTACHMENT_FILENAME_KEY + "=" + fileName + "");
		ServletOutputStream out = response.getOutputStream();
		byte[] temp = new byte[bufferSize];
		int read;
		while ((read = inputStream.read(temp)) > 0) {
			out.write(temp, 0, read);
		}
		IOUtils.close(inputStream);
		out.flush();
		out.close();
	}

}
